package com.dougs.timehandler.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.dougs.timehandler.receiver.LockScreenReceiver;

public class LockForegroundService extends Service {

    private static final String CHANNEL_ID = "ForegroundServiceChannel";
    private static final int NOTIFICATION_ID = 1;
    private int REQUEST_CODE_LOCK_SCREEN = 10000;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int lockTime = intent.getIntExtra("lockTime", 0);

        startForeground(NOTIFICATION_ID, createNotification(lockTime));

        //触发锁屏定时
         lockScreenBroadcast(lockTime);

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //不需要绑定
        return null;
    }

    private void lockScreenBroadcast(int num) {
        Intent intent = new Intent(this, LockScreenReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE_LOCK_SCREEN, intent, 0);

        // 设置num分钟后触发
        long triggerTime = System.currentTimeMillis() + num * 60 * 1000;
//        long triggerTime = System.currentTimeMillis() + num * 1000;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
    }

    private Notification createNotification(int lockTime) {
        // 创建通知频道
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "锁屏通知", NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);

        // 创建通知
        Notification.Builder builder = new Notification.Builder(this, CHANNEL_ID)
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentTitle("锁屏服务")
                .setContentText("定时"+lockTime+"分钟锁屏")
                .setPriority(Notification.PRIORITY_DEFAULT)
                .setCategory(Notification.CATEGORY_SERVICE);

        return builder.build();
    }

}
